package com.yh.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 
 * <pre>
 * - 字符集编码过滤器
 * - 初始化参数
 *  charset : 请求的字符集编码
 *  contentType : 响应的文档类型
 * ClassName : com.yh.filter.CharsetFilter
 * &#64;author 湛锋
 * Date : 2020年8月6日 下午7:07:25
 * </pre>
 *
 */
public class CharsetFilter implements Filter {

	private String charset = "UTF-8";
	private String contentType = "text/html;charset=UTF-8";

	/**
	 * - 对Filter的初始化参数进行判断
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		if (filterConfig.getInitParameter("charset") != null) {
			charset = filterConfig.getInitParameter("charset");
		}
		if (filterConfig.getInitParameter("contentType") != null) {
			contentType = filterConfig.getInitParameter("contentType");
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request.getCharacterEncoding() == null) {
			request.setCharacterEncoding(charset);
		}
		if (response.getCharacterEncoding() == null) {
			response.setCharacterEncoding(contentType);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}
